package com.itheima.health.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.RoleDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.Menu;
import com.itheima.health.pojo.Role;
import com.itheima.health.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@DubboService
@Slf4j
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleDao roleDao;
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<Role> page = roleDao.selectByQueryString(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page);
    }

    @Override
    public Role findById(Integer id) {
        return roleDao.selectById(id);
    }

    @Override
    @Transactional
    public void add(Integer[] permissionIds, Role role, Integer[] menuIds) {
        roleDao.addrole(role);
        roleDao.addpermissionIds(permissionIds,role.getId());
        roleDao.addmenuIds(menuIds,role.getId());
    }

    @Override
    @Transactional
    public void edit(Integer[] permissionIds, Role role, Integer[] menuIds) {
        roleDao.edit(role);
        roleDao.deleteByRoleid(role.getId());
        roleDao.deletemByRoleid(role.getId());
        roleDao.addpermissionIds(permissionIds,role.getId());
        roleDao.addmenuIds(menuIds,role.getId());
    }

    @Override
    @Transactional
    public void del(Integer id) {
        try {
            roleDao.deletemByRoleid(id);
            roleDao.deleteByRoleid(id);
            roleDao.del(id);
        } catch (Exception e) {
            throw new BusinessRuntimeException("数据关联无法删除");
        }
    }

    @Override
    public List<Role> findAll() {
        return roleDao.findAll();
    }

    @Override
    public Integer[] findRoleIdsByUserId(Integer id) {
        return roleDao.findRoleIdsByUserId(id);
    }

    @Override
    public List<Menu> findMenuAll() {

        return roleDao.findMenuAll();
    }

    @Override
    public Integer[] findMenuIdsByRoleId(Integer id) {
        return roleDao.findMenuIdsByRoleId(id);
    }
}
